/* components */
import ChatAIMessageItem from '@src/component/business/BizChatPanel/chat/components/message-item'
import ChatAIMessageItemLoading from '@src/component/business/BizChatPanel/chat/components/message-item-loading'
/* enum */
import { ChatLikeStatusEnum, ChatSourceDocumentTypeEnum, ComponentNameEnum } from '@src/component/business/BizChatPanel/chat/model/enum'
/* hooks */
import { useChatFetchDisLikeMessage, useChatFetchLikeMessage } from '@src/component/business/BizChatPanel/chat/hooks'
/* model */
import { OpenAIMessageItemType } from '@src/component/business/BizChatPanel/chat/model'
/* scss */
import '@src/component/business/BizChatPanel/chat/components/message-list/index.scss'
/* vue */
import { computed, defineComponent, PropType } from 'vue'
/* util */
import { getAssistantLoadingMessage, isNotUserMessage, isUserMessage } from '@src/component/business/BizChatPanel/chat/util'
import { GetChatDisLikeMessageModel, GetChatDisLikeMessageShareModel, GetChatLikeMessageModel, GetChatLikeMessageShareModel } from '@model/param/in/AI'
import { isFalsy, isNotEmpty } from '@src/util/type'
import { stringify } from '@src/util/lang/object'
import { message } from '@src/util/message'

export type ChatAIMessageListProps = {
  value: OpenAIMessageItemType[];
  isShare: boolean;
  isStreaming: boolean;
}

export interface ChatAIMessageListSetupState {
  
}

enum ChatAIMessageListEventEnum {
  Input = 'input',
  Refresh = 'refresh',
  Stop = 'stop',
}

export default defineComponent({
  name: ComponentNameEnum.ChatAIMessageList,
  components: {
    [ChatAIMessageItem.name]: ChatAIMessageItem,
    [ChatAIMessageItemLoading.name]: ChatAIMessageItemLoading,
  },
  emits: [
  ],
  props: {
    isShare: {
      type: Boolean,
      default: false
    },
    isStreaming: {
      type: Boolean,
      default: false
    },
    robotId: {
      type: String,
      default: ''
    },
    robotAppId: {
      type: String as PropType<string>,
      default: ''
    },
    tenantId: {
      type: String,
      default: ''
    },
    userId: {
      type: String,
      default: ''
    },
    value: {
      type: Array as PropType<OpenAIMessageItemType[]>,
      default: () => ({})
    }
  },
  setup(props: ChatAIMessageListProps, { slots, emit }) {
    
    // 是否是外部分享的
    const _isShare = computed(() => props.isShare)
    
    const { fetchLikeMessage } = useChatFetchLikeMessage(_isShare)
    const { fetchDisLikeMessage } = useChatFetchDisLikeMessage(_isShare)
    
    return {
      fetchLikeMessage,
      fetchDisLikeMessage
    }
    
  },
  computed: {
    
  },
  methods: {
    /** 
     * @description 点赞
    */
    onLikeHandler(item: OpenAIMessageItemType) {
      
      const itemIndex = this.value.findIndex((value) => value.id == item.id)
      const prevItem = this.value[itemIndex - 1]
      
      if (itemIndex < 0 || isFalsy(prevItem)) {
        return
      }
      
      if (isNotUserMessage(prevItem)) {
        return
      }
      
      const businessSourceDocuments = item?.businessSourceDocuments || []
      
      let params: GetChatLikeMessageShareModel = {
        conversationContentId: item.id,
        question: prevItem.content || '',
        answer: item.content || '',
        sourceDocumentList: isNotEmpty(businessSourceDocuments) ? stringify(businessSourceDocuments) : '',
        sourceDocumentType: ChatSourceDocumentTypeEnum.Wiki,
        robotId: this.robotId,
        robotAppId: this.robotAppId
      }
      
      if (this.isShare) {
        params.loginUserId = this.userId
        params.tenantId = this.tenantId
      }
      
      // 更新状态
      if (item.likeStatus == ChatLikeStatusEnum.Like) {
        item.likeStatus = ChatLikeStatusEnum.Empty
        message.info('已取消反馈')
      } else {
        item.likeStatus = ChatLikeStatusEnum.Like
        message.info('感谢您的反馈')
      }
      
      this.fetchLikeMessage(params).catch(() => {
        item.likeStatus = null
      })
      
    },
    /** 
     * @description 点踩
    */
    onDislikeHandler(item: OpenAIMessageItemType) {
      
      const itemIndex = this.value.findIndex((value) => value.id == item.id)
      const prevItem = this.value[itemIndex - 1]
      
      if (itemIndex < 0 || isFalsy(prevItem)) {
        return
      }
      
      if (isNotUserMessage(prevItem)) {
        return
      }
      
      const businessSourceDocuments = item?.businessSourceDocuments || []
      
      let params: GetChatDisLikeMessageShareModel = {
        conversationContentId: item.id,
        question: prevItem.content || '',
        answer: item.content || '',
        sourceDocumentList: isNotEmpty(businessSourceDocuments) ? stringify(businessSourceDocuments) : '',
        sourceDocumentType: ChatSourceDocumentTypeEnum.Wiki,
        robotId: this.robotId,
        robotAppId: this.robotAppId
      }
      
      if (this.isShare) {
        params.loginUserId = this.userId
        params.tenantId = this.tenantId
      }
      
      // 更新状态
      if (item.likeStatus == ChatLikeStatusEnum.DisLike) {
        item.likeStatus = ChatLikeStatusEnum.Empty
        message.info('已取消反馈')
      } else {
        item.likeStatus = ChatLikeStatusEnum.DisLike
        message.info('感谢您的反馈')
      }
      
      this.fetchDisLikeMessage(params).catch(() => {
        item.likeStatus = null
      })
      
    },
    /** 
     * @description 重新回答
    */
    onRefreshHandler() {
      // @ts-ignore
      this.$emit(ChatAIMessageListEventEnum.Refresh)
    },
    onStopHandler() {
      // @ts-ignore
      this.$emit(ChatAIMessageListEventEnum.Stop)
    }
  },
  render() {
    return (
      <div class={ComponentNameEnum.ChatAIMessageList}>
        
        {/* start 消息列表 */}
        {this.value.map((item, index) => {
          
          const isLast = index === this.value.length - 1
          const isFirst = index === 0
          const preItem = this.value[index - 1]
          
          const isLoading = isLast && item?.content == getAssistantLoadingMessage()?.content
          
          if (isLoading) {
            return (
              <chat-ai-message-item-loading 
                item={item}
                isFirst={isFirst}
                isLast={isLast}
                onStop={this.onStopHandler}
              >
              </chat-ai-message-item-loading>
            )
          }
          
          return (
            <chat-ai-message-item 
              item={item}
              preItem={preItem}
              isFirst={isFirst}
              isLast={isLast}
              isStreaming={this.isStreaming}
              onLike={this.onLikeHandler}
              onDislike={this.onDislikeHandler}
              onRefresh={this.onRefreshHandler}
            >
            </chat-ai-message-item>
          )
          
        })}
        {/* end 消息列表 */}
        
      </div>
    ) as any
  }
})
